﻿#include <cstdint>
#include <iostream>
#include <string.h>
#include <cstdio>
#include "ExecutionEngine/cgra_sim_api.h"

/*   hash padding     64 --->   32*/
void hash_padding(int algo, unsigned char* in, uint32_t in_len, unsigned char* out, uint32_t* out_len)
{

    int i;
    uint32_t size_bit = in_len * 8;

    if (algo != CK_MD_SHA384)
    {
        *out_len = (in_len + 72) / 64 * 64;
        memcpy(out, in, in_len);
        out[in_len] = 0x80;

        if (algo != CK_MD_MD5)   // algo :0 md5  :1 other
        {
            for (i = 0; i < 4; i++)
            {
                //				out[*out_len - 4 + i] = size_bit %256;
                out[*out_len - 1 - i] = size_bit % 256;
                size_bit /= 256;
            }
        }
        else
        {
            for (i = 0; i < 4; i++)
            {
                out[*out_len - 8 + i] = size_bit % 256;
                size_bit /= 256;
                //out[*out_len - 5 - i] = size_bit %256;
            }
        }
    }
    else
    {
        *out_len = (in_len + 144) / 128 * 128;
        memcpy(out, in, in_len);
        out[in_len] = 0x80;
        for (i = 0; i < 16; i++)
        {
            out[*out_len - 1 - i] = size_bit % 256;
            size_bit /= 256;
        }
    }
}

void pkcs7_padding(unsigned char* in, uint32_t in_len, unsigned char* out, uint32_t* out_len)
{
    // 计算填充字节数 (1 <= pad_len <= 16)
    uint32_t block_size = 16; // AES块大小固定16字节
    uint32_t pad_len = block_size - (in_len % block_size);
    
    // 拷贝原始数据
    memcpy(out, in, in_len);
    
    // 填充字节（每个字节值为pad_len）
    for (uint32_t i = 0; i < pad_len; ++i) {
        out[in_len + i] = static_cast<unsigned char>(pad_len);
    }
    // 返回填充后长度
    *out_len = in_len + pad_len;
}

